package cn.dengta.webapp.trade.dto.common;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

import cn.dengta.common.model.ValueProxyImpl;
import cn.dengta.context.model.WesKit;
import cn.dengta.webapp.trade.model.PayPlatform;
import lombok.Getter;
import lombok.Setter;
import me.codeplayer.util.X;

/** 支付渠道配置 */
@Getter
@Setter
public class PayConfig implements Serializable {

	/** 渠道配置 */
	private Map<WesKit, ChannelConfig> pay;
	/**
	 * ios支付平台
	 */
	private Map<WesKit, IosPayPlatform> iosPlatform;

	public static PayConfig getDefault() {
		final PayConfig config = new PayConfig();
		config.setPay(new HashMap<>());
		for (WesKit wesKit : WesKit.values()) {
			if (!wesKit.isInterior()) {
				continue;
			}
			config.getPay().put(wesKit, getDefaultChannel());
		}
		return config;
	}

	public ChannelConfig findByWesKitOrDef(WesKit wesKit) {
		if (!wesKit.isInterior()) {
			return null;
		}
		ChannelConfig config = pay.get(wesKit);
		return config != null ? config : getDefaultChannel();
	}

	public static ChannelConfig getDefaultChannel() {
		return new ChannelConfig(PayPlatform.Wxpay, Set.of(PayPlatform.Wxpay, PayPlatform.Alipay), 8L);
	}

	@Setter
	@Getter
	public static class ChannelConfig {

		/** 默认支付平台 */
		public PayPlatform defPlatform;
		/** 显示的支付平台 */
		public Set<PayPlatform> showPlatform;
		/** 提现渠道 */
		public Long cashId;

		public ChannelConfig() {
		}

		public ChannelConfig(PayPlatform defPlatform, Set<PayPlatform> showPlatform, Long cashId) {
			this.defPlatform = defPlatform;
			this.showPlatform = showPlatform;
			this.cashId = cashId;
		}

		public Integer getDefPlatform() {
			return ValueProxyImpl.value(defPlatform);
		}

		public Set<Integer> getShowPlatform() {
			if (X.isValid(showPlatform)) {
				return showPlatform.stream().map(ValueProxyImpl::value).collect(Collectors.toSet());
			}
			return null;
		}

		public void setDefPlatform(Integer defPlatform) {
			this.defPlatform = PayPlatform.of(defPlatform);
		}

		public void setShowPlatform(Set<Integer> showPlatform) {
			this.showPlatform = showPlatform.stream().map(PayPlatform::of).collect(Collectors.toSet());
		}

	}

	public Map<WesKit, IosPayPlatform> getIosPlatform() {
		if (iosPlatform == null) {
			iosPlatform = new HashMap<>();
			for (WesKit wesKit : WesKit.values()) {
				if (wesKit.isInterior()) {
					IosPayPlatform pay = new IosPayPlatform();
					pay.setPay(true);
					iosPlatform.put(wesKit, pay);
				}
			}
		}
		return iosPlatform;
	}

	@Getter
	@Setter
	public static class IosPayPlatform {

		/**
		 * ios支付平台
		 * true=APP内购
		 * false=H5
		 */
		private Boolean pay;
		/** h5支付路径 */
		private String h5PayUrl;

	}

}
